package com.jyxd.web.service.assessment.basic.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyxd.web.dao.basic.BedBindDeviceMapper;
import com.jyxd.web.data.basic.BedBindDevice;
import com.jyxd.web.data.user.User;
import com.jyxd.web.service.assessment.basic.IBedBindDeviceService;
import com.jyxd.web.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;

import static com.jyxd.web.util.UUIDUtil.getUUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2022-09-23
 */
@Service
public class BedBindDeviceServiceImpl extends ServiceImpl<BedBindDeviceMapper, BedBindDevice> implements IBedBindDeviceService {

    @Override
    public BedBindDevice selectOneByBedCodeAndTenantId(String bedCode, String tenantId, Date dataTime) {
        return this.baseMapper.selectOneByBedCodeAndTenantId(bedCode, tenantId, dataTime);
    }

    @Override
    public void bind(User user, String bedCode, String deviceId, String dateTime, int deviceType) {
        Date bindTime = new Date();
        if (StringUtils.isNotBlank(dateTime)) {
            try {
                bindTime = DateUtil.yyyyMMddHHmmssSdfToDate(dateTime);
            } catch (ParseException e) {
            }
        }
        this.baseMapper.unbindByBedCodeOrDeviceId(bedCode, deviceId, bindTime, deviceType, user.getId());

        BedBindDevice bindDevice = new BedBindDevice();
        bindDevice.setId(getUUID());
        bindDevice.setBindTime(bindTime);
        bindDevice.setDeviceId(deviceId);
        bindDevice.setBedCode(bedCode);
        bindDevice.setDeviceType(deviceType);
        bindDevice.setTenantId(user.getTenantId());
        bindDevice.setCreateTime(new Date());
        bindDevice.setCreateUser(user.getId());
        this.save(bindDevice);
    }
}
